import Taro from '@tarojs/taro';
import store from '@/store/user';
import config from './config'
import user from '@/store/user';
import { tarBarPages } from '@/utils';

let timer
type MethodKeys = 'OPTIONS' | 'GET' | 'HEAD' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'TRACE' | 'CONNECT';
const Request = (url, params, method: MethodKeys = 'GET') => {
  const userInfo = store.info
  const token = userInfo?.token || ''
  return Taro.request({
    url: url.indexOf('http') === 0 ? url : config.BASE_URL + url, // 请求的 URL
    method: method, // HTTP 请求方法
    data: params,
    header: {
      'content-type': 'application/json',
      token,
      AppNice: 'tr-api',
      AppPassWd: 'tr-api',
      client_id: 'webApp',
      client_secret: 'webApp',
    }
  }).then(res => {
    if (res.data.code === 0) {
      return res.data
    } else if (res.data.code === 401) {
      const pages = Taro.getCurrentPages()
      const page = pages[pages.length - 1]
      // // 避免反复编码
      const fullPath = decodeURIComponent(page.$taroPath)
      // 没权限时清空已有身份信息
      user.updateInfo({})
      if (timer) {
        clearTimeout(timer)
      }
      timer = setTimeout(() => {
        // tab页面不重定向
        if (!tarBarPages.includes(page.route || '')){
          if (page.route === 'pages/mine/index') {
            Taro.redirectTo({
              url: '/pages/login/index'
            })
          } else {
            Taro.redirectTo({
              url: `/pages/login/index?redirect=${encodeURIComponent(`/${fullPath}`)}`
            })
          }
        }
      }, 200)
    } else if (url.indexOf('http') === 0) {
      // 部分第三方接口不拦截
      return res
    }
    throw res.data || res
  });
}
Request.post = (url, params = {}) => Request(url, params, 'POST')
Request.get = (url, params = {}) => Request(url, params, 'GET')
Request.put = (url, params = {}) => Request(url, params, 'PUT')
Request.delete = (url, params = {}) => Request(url, params, 'DELETE')

const http = Request
export default http
